package cn.smbms.controller;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    private Logger logger = Logger.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @RequestMapping(value="/list.html")
    public String getUserList(Model model,
          @RequestParam(value="queryname",required=false) String queryUserName,
          @RequestParam(value="queryUserRole",required=false) String queryUserRole,
          @RequestParam(value="pageIndex",required=false) String pageIndex){

        logger.info("getUserList ---- > queryUserName: " + queryUserName);
        logger.info("getUserList ---- > queryUserRole: " + queryUserRole);
        logger.info("getUserList ---- > pageIndex: " + pageIndex);


        int _queryUserRole = 0;
        List<User> userList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;

        if(queryUserName == null){
            queryUserName = "";
        }
        if(queryUserRole != null && !queryUserRole.equals("")){
            _queryUserRole = Integer.parseInt(queryUserRole);
        }

        if(pageIndex != null){
            currentPageNo = Integer.valueOf(pageIndex);
        }

        //总数量（表）
        int totalCount	= userService.getUserCount(queryUserName,_queryUserRole);
        //总页数
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();

        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }
        userList = userService.getUserList(queryUserName,_queryUserRole,currentPageNo,pageSize);
        model.addAttribute("userList", userList);
        List<Role> roleList = null;
        roleList = roleService.getRoleList();
        model.addAttribute("roleList", roleList);
        model.addAttribute("queryUserName", queryUserName);
        model.addAttribute("queryUserRole", queryUserRole);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", currentPageNo);

        return "userlist";
    }


    @RequestMapping(value="/add.html")
    public String addUser(){
        return "useradd";
    }


    @RequestMapping(value="/addsave.html",method=RequestMethod.POST)
    public String addUserSave(User user,HttpServletRequest request, HttpSession session,@RequestParam(value="a_idPicPath",required=false)MultipartFile attach){

        String idPicPath = null;

        if (!attach.isEmpty()) {
            //文件上传到哪里？目标路径
            String path = session.getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
            logger.info("uploadFile path ============== > "+path);
            String oldFileName = attach.getOriginalFilename();//原文件名
            logger.info("uploadFile oldFileName ============== > "+oldFileName);
            String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀
            logger.debug("uploadFile prefix============> " + prefix);
            int filesize = 5000000;
            logger.debug("uploadFile size============> " + attach.getSize());
            if(attach.getSize() >  filesize){//上传大小不得超过 500k
                request.setAttribute("uploadFileError", " * 上传大小不得超过 500k");
                return "useradd";
            } else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {//上传图片格式不正确

                String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";
                logger.debug("new fileName======== " + fileName);

                File targetFile = new File(path, fileName);

                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }

                try {
                    //将文件写入到目标文件
                    attach.transferTo(targetFile);
                }catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    request.setAttribute("uploadFileError", " * 上传失败！");
                    return "useradd";
                }

                idPicPath = path+File.separator+fileName;
            }else{
                request.setAttribute("uploadFileError", " * 上传图片格式不正确");
                return "useradd";
            }



        }

        User loginUser =  (User) session.getAttribute(Constants.USER_SESSION);

        user.setCreatedBy(loginUser.getId());
        user.setCreationDate(new Date());

        user.setIdPicPath(idPicPath);

        boolean result = userService.add(user);

        if (result) {
            return "redirect:/user/list.html";
        }

        return "useradd";
    }

    @RequestMapping(value="/update.html")
    public String updateUser(Integer uid,Model model){
        logger.debug(uid);

        User user = userService.getUserById(uid);

        model.addAttribute(user);
        return "usermodify";
    }

    @RequestMapping(value="/updatesave.html",method=RequestMethod.POST)
    public String addUserSave(User user, HttpSession session){
        User loginUser =  (User) session.getAttribute(Constants.USER_SESSION);

        user.setModifyBy(loginUser.getId());
        user.setModifyDate(new Date());

        boolean result = userService.update(user);

        if (result) {
            return "redirect:/user/list.html";
        }

        return "usermodify";
    }

    @RequestMapping(value = "/view/{id}")
    public String view(@PathVariable Integer id, Model model){

        model.addAttribute(userService.getUserById(id));

        return "userview";
    }

    @RequestMapping(value="/ucexist.html")
    @ResponseBody
    public Object userCodeIsExit(@RequestParam String userCode) throws Exception {
        logger.debug("userCodeIsExit userCode===================== "+userCode);
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(StringUtils.isNullOrEmpty(userCode)){
            resultMap.put("userCode", "exist");
        }else{
            User user = userService.selectUserCodeExist(userCode);
            if(null != user)
                resultMap.put("userCode", "exist");
            else
                resultMap.put("userCode", "noexist");
        }
        return JSONArray.toJSONString(resultMap);
    }

    @RequestMapping(value="/view",method=RequestMethod.GET)
    @ResponseBody
    public User view(@RequestParam Integer id){
        logger.debug("view id: "+id);
        User user = new User();
        try {
            user = userService.getUserById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }
}
